<?php
/**
 * Rate posts
 *
 * @author	Martin Hesse <info@mh-dev.de>
 * @package	MH-Dev.-Board
 */
class RateController extends Zend_Controller_Action
{
	private $registry; // registry
	private $auth; // user-values
	
	public function init()
	{		
		// registry
		$registry = Zend_Registry::getInstance();
		$this->registry = $registry;
		
		// auth
		$auth = Zend_Auth::getInstance();
    	$this->view->auth = $auth->hasIdentity();
    	
    	if($auth->hasIdentity())
    	{
    		$this->view->auth_role 			= $auth->getIdentity()->role;
    		$this->view->username 			= $auth->getIdentity()->username;
    		$this->view->auth_uid			= $auth->getIdentity()->uid;
    		$this->view->unread_messages	= $auth->getIdentity()->count_unread_messages;
    	}
    	else
    	{
    		$this->view->username 	= 'Gast';
    	}

    	$this->auth = $auth;
    	
    	// lang
		$this->view->translate = Zend_Registry::get('lang');
		
		// flash messenger
		$this->view->flashMessenger	= $this->_helper->FlashMessenger;
		
		// include jquery
		$baseurl = new MHDEV_View_Helper_BaseUrl();
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/css/jquery.css');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/jquery-1.3.2.min.js');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/jquery-ui-1.7.2.custom.min.js');
	}
	
	
	
	public function indexAction()
	{
		// nothing here
	}
	
	
	/*
	 * Request rating from a user
	 * 
	 * @param string $value
	 * @param int $uid
	 */
	public function requestAction()
	{
		// disable layout
		Zend_Layout::getMvcInstance()->disableLayout();
		
		// settings
		$settings	= Zend_Registry::getInstance()->get('settings');
		
		// db
		$rates		= new Rates();
		
		// params
		$value 		= $this->_request->getParam('val', 0);
		$uid		= $this->_request->getParam('uid', 0);

		$valid_value = array('up', 'down');
		
		if($settings['allow_rating'] == 1 && $this->auth->hasIdentity() && $uid > 0 && in_array($value, $valid_value))
		{
			$user_uid	= $this->auth->getIdentity()->uid;
			$checkRate	= $rates->fetchAll('user_uid = ' . $user_uid . ' AND post_uid = ' . $uid);
			
			if($checkRate->count() == 0)
			{
				if($rates->insert(array(
					'post_uid'	=> $uid,
					'user_uid'	=> $user_uid,
					'value'		=> $value,
					'date'		=> new Zend_Db_Expr("NOW()")
				)))
				{
					return print Zend_Registry::get('lang')->_('rate_' . $value);
				}
			}
			else
			{
				return print Zend_Registry::get('lang')->_('rate_voted');
			}
		}
		else
		{
			return print Zend_Registry::get('lang')->_('rate_error');
		}
	}
}
?>